package vpndao

import (
	"vpn-management-server/logger"
	"vpn-management-server/src/dao"
	"vpn-management-server/src/model/vpnmodel"
)

func AddVpnServerInfo(info *vpnmodel.VpnServerInfo) error {
	sqlStr := "INSERT INTO vpn_server_info(name,client_prefix,is_inner,ip,port,sockets_port,remote_prefix,mtu,inner_ips,ug_id,timestamp)value(?,?,?,?,?,?,?,?,?,?,?)"
	if _, err := dao.GMysqlDB.Conn.Exec(sqlStr, info.Name, info.ClientPrefix, info.IsInner, info.IP, info.Port, info.Socks5Port, info.RemotePrefix, info.Mtu, info.InnerIP, info.UGroupID, info.TimeStamp); err != nil {
		logger.Logger.Error(err)
		return err
	}
	return nil
}

func DeleteVpnServerInfoByID(id int) error {
	sqlStr := "DELETE FROM vpn_server_info WHERE id = ?"
	if _, err := dao.GMysqlDB.Conn.Exec(sqlStr, id); err != nil {
		logger.Logger.Error(err)
		return err
	}
	return nil
}

func GetUGroupVpnServerInfosByPage(ugid int, pageNo, pageSize int) []*vpnmodel.VpnServerInfo {
	start := (pageNo - 1) * pageSize
	var VpnServerInfo []*vpnmodel.VpnServerInfo
	sqlStr := "SELECT * FROM vpn_server_info where ug_id = ? limit ?,?"
	if err := dao.GMysqlDB.Conn.Select(&VpnServerInfo, sqlStr, ugid, start, pageSize); err != nil {
		logger.Logger.Error(err)
		return nil
	}
	return VpnServerInfo
}

func GetVpnServerInfosCount(ugid int) int {
	var count int
	sqlStr := "SELECT COUNT(*) FROM vpn_server_info where ug_id = ?"
	if err := dao.GMysqlDB.Conn.Get(&count, sqlStr, ugid); err != nil {
		logger.Logger.Error(err)
		return -1
	}
	return count
}

func GetAllVpnServerInfosByUGroupID(ugid int) []*vpnmodel.VpnServerInfo {
	var VpnServerInfo []*vpnmodel.VpnServerInfo
	sqlStr := "SELECT * FROM vpn_server_info where ug_id = ?"
	if err := dao.GMysqlDB.Conn.Select(&VpnServerInfo, sqlStr, ugid); err != nil {
		logger.Logger.Error(err)
		return nil
	}
	return VpnServerInfo
}

func GetAllVpnServerNameInfosByUGroupID(ugid int) []*vpnmodel.VpnServerNameInfo {
	var VpnServerNameInfos []*vpnmodel.VpnServerNameInfo
	sqlStr := "SELECT id,name FROM vpn_server_info where ug_id = ?"
	if err := dao.GMysqlDB.Conn.Select(&VpnServerNameInfos, sqlStr, ugid); err != nil {
		logger.Logger.Error(err)
		return nil
	}
	return VpnServerNameInfos
}

// GetVpnServerInfoByID 不能通过名字获取 名字可能会有重复 只能通过ID获取
func GetVpnServerInfoByID(id int) *vpnmodel.VpnServerInfo {
	var VpnServerInfo vpnmodel.VpnServerInfo
	sqlStr := "SELECT * FROM vpn_server_info where id = ?"
	if err := dao.GMysqlDB.Conn.Get(&VpnServerInfo, sqlStr, id); err != nil {
		logger.Logger.Error(err)
		return nil
	}
	return &VpnServerInfo
}
